﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api;
using Top.Api.Domain;

namespace KSGJ
{
    public partial class Logincheck : System.Web.UI.Page
    {
        private static string appkey = System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString();
        private static string appsecret = System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString();
        private static string appurl = System.Configuration.ConfigurationManager.AppSettings["AppUrl"].ToString();
        private static string itemcode = System.Configuration.ConfigurationManager.AppSettings["ItemCode"].ToString();
        private static ITopClient client = new DefaultTopClient(appurl, appkey, appsecret);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (CheckTopSign(Request.QueryString["top_parameters"] + Request.QueryString["top_session"], Request.QueryString["top_sign"]))
                {
                    string strParameters = Request.QueryString["top_parameters"];
                    string usNick = GetParameters(strParameters, "visitor_nick");
                    VasSubscribeGetRequest vreq = new VasSubscribeGetRequest();
                    vreq.Nick = usNick;
                    vreq.ArticleCode = "ts-12715";
                    VasSubscribeGetResponse vrep = client.Execute(vreq);
                    ArticleUserSubscribe userlist = vrep.ArticleUserSubscribes.Find(delegate(ArticleUserSubscribe aus) { return aus.ItemCode == itemcode; });
                    if (userlist != null)
                    {
                        if (DateTime.Parse(userlist.Deadline).CompareTo(DateTime.Now) < 0)
                        {
                            string path = Page.ResolveUrl("http://fuwu.taobao.com/service/service.htm?service_id=12715");
                            string js = "<script language=javascript>alert('您的使用时间已到期，请重新订购后再试');top.window.location.replace('" + path + "')</script>";
                            HttpContext.Current.Response.Write(js);
                            return;
                        }
                    }
                    else
                    {
                        string path = Page.ResolveUrl("error.htm");
                        string js = "<script language=javascript>top.window.location.replace('" + path + "')</script>";
                        HttpContext.Current.Response.Write(js);
                        return;
                    }
                    //验证是否经过短授权
                    if (Session["expires"] == null)
                    {
                        if (GetParameters(strParameters, "hra_expires_in") == "")
                        {
                            string path = Page.ResolveUrl("http://container.api.taobao.com/container?appkey=" + System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString() + "&scope=promotion");
                            string js = "<script language=javascript>alert('请再次进行短授权登录');top.window.location.replace('" + path + "')</script>";
                            HttpContext.Current.Response.Write(js);
                            return;
                        }
                        else
                        {
                            Session.Add("expires", GetParameters(strParameters, "hra_expires_in"));
                        }
                    }
                    //string subNick = GetParameters(strParameters, "sub_taobao_user_nick");
                    //string subId = GetParameters(strParameters, "sub_taobao_user_id");
                    //if (subNick != string.Empty)
                    //{
                    //    VasSubscribeGetRequest vreq = new VasSubscribeGetRequest();
                    //    vreq.Nick = usNick;
                    //    vreq.ArticleCode = "ts-12715";
                    //    VasSubscribeGetResponse vrep = client.Execute(vreq);
                    //    ArticleUserSubscribe userlist = vrep.ArticleUserSubscribes.Find(delegate(ArticleUserSubscribe aus) { return aus.ItemCode == itemcode; });

                    //    if (userlist != null)
                    //    {
                    //        if (DateTime.Parse(userlist.Deadline).CompareTo(DateTime.Now) < 0)
                    //        {
                    //            string path = Page.ResolveUrl("http://fuwu.taobao.com/service/service.htm?service_id=12715");
                    //            string js = "<script language=javascript>alert('您的使用时间已到期，请重新订购后再试');top.window.location.replace('" + path + "')</script>";
                    //            HttpContext.Current.Response.Write(js);
                    //            return;
                    //        }
                    //        else
                    //        {
                    //            Session.Add("subNick", subNick);
                    //            Session.Add("subId", subId);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        string path = Page.ResolveUrl("error.htm");
                    //        string js = "<script language=javascript>top.window.location.replace('" + path + "')</script>";
                    //        HttpContext.Current.Response.Write(js);
                    //        return;
                    //    }
                    //    //Session.Add("subNick", subNick);
                    //    //Session.Add("subId", subId);
                    //}
                    //else
                    //{
                    //    //if (Session["expires"] == null)
                    //    //{
                    //    //    if (GetParameters(strParameters, "hra_expires_in") == "")
                    //    //    {
                    //    //        //string path = Page.ResolveUrl("http://container.api.taobao.com/container?appkey=" + System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString() + "&scope=promotion");
                    //    //        string path = Page.ResolveUrl("http://container.api.taobao.com/container?appkey=" + System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString());
                    //    //        string js = "<script language=javascript>alert('请再次进行短授权登录');top.window.location.replace('" + path + "')</script>";
                    //    //        HttpContext.Current.Response.Write(js);
                    //    //        return;
                    //    //    }
                    //    //    else
                    //    //    {
                    //    //        Session.Add("expires", GetParameters(strParameters, "hra_expires_in"));
                    //    //    }
                    //    //}
                    //}
                    Session.Add("sessionKey", Request.QueryString["top_session"]);//取得用户session
                    Session.Add("usNick", usNick);//取得用户昵称
                    Response.Redirect("/ksgj/Index.aspx");
                    //Response.Redirect("/Index.aspx");
                }
                else
                {
                    string path = Page.ResolveUrl("http://container.api.taobao.com/container?appkey=" + System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString() + "&scope=promotion");
                    //string path = Page.ResolveUrl("http://container.api.taobao.com/container?appkey=" + System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString());
                    string js = "<script language=javascript>alert('签名验证失败，请重试！');top.window.location.replace('" + path + "')</script>";
                    HttpContext.Current.Response.Write(js);
                }
            }
        }

        /// <summary>
        /// 验证TOP签名
        /// </summary>
        /// <param name="parameters">topParamters</param>
        /// <param name="topsign">topSign</param>
        /// <returns>boolen</returns>
        public static bool CheckTopSign(string parameters, string topsign)
        {
            System.Text.StringBuilder strResult = new System.Text.StringBuilder();
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            strResult.Append(System.Configuration.ConfigurationManager.AppSettings["AppKey"].ToString());
            strResult.Append(parameters);
            strResult.Append(System.Configuration.ConfigurationManager.AppSettings["AppSecret"].ToString());
            byte[] bytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strResult.ToString()));
            return System.Convert.ToBase64String(bytes) == topsign;
        }

        /// <summary>
        /// 解析回调地址中top_parameters中的值
        /// </summary>
        /// <param name="key">取值关键词</param>
        /// <returns></returns>
        public string GetParameters(string parameters, string key)
        {
            string ret = string.Empty;
            try
            {
                string str = Base64ToString(parameters);
                string[] param = str.Split('&');
                for (int i = 0; i < param.Length; i++)
                {
                    string[] info = param[i].Split('=');
                    if (info[0].ToLower() == key.ToLower())
                    {
                        ret = info[1];
                        break;
                    }
                }
            }
            catch (Exception exp)
            {
                //
            }
            return ret;
        }

        /// <summary>
        /// Base64 解密
        /// </summary>
        /// <param name="str">已加密字符串</param>
        /// <returns>源字符串</returns>
        public string Base64ToString(string str)
        {
            try
            {
                return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(str));
            }
            catch (Exception)
            {
                return "-1";
                throw;
            }

        }
    }
}